package router

import (
	"shop-manager/internal/do"
	"shop-manager/internal/repos/category"
	"shop-manager/utils"

	"github.com/gin-gonic/gin"
	"github.com/samber/lo"
)

func RegisterCategoryMeta(api *gin.RouterGroup,
	categoryRepo *category.CategoryRepo,
	handleBizRsp func(ctx *gin.Context, rsp any, err error),
	handleBizListRsp func(ctx *gin.Context, rsp any, total int64, err error),
) {
	categoryApiGroup := api.Group("/category_meta")
	{
		categoryApiGroup.POST("/create", func(ctx *gin.Context) {
			type ReqJson struct {
				Name         string
				CategoryType do.CategoryType
			}
			var req ReqJson
			if err := ctx.BindJSON(&req); err != nil {
				return
			}
			name := req.Name
			names := utils.SplitString(name, "\n")
			metas := lo.Map(lo.Uniq(names), func(item string, index int) *do.CategoryMeta {
				return &do.CategoryMeta{
					Name:         item,
					CategoryType: req.CategoryType,
				}
			})

			err := categoryRepo.CreateCategoryMetaInBatches(ctx, metas)
			handleBizRsp(ctx, 0, err)
		})

		categoryApiGroup.POST("/update", func(ctx *gin.Context) {
			type ReqJson struct {
				ID           int
				Name         string
				CategoryType do.CategoryType
			}
			var req ReqJson
			if err := ctx.BindJSON(&req); err != nil {
				return
			}
			err := categoryRepo.UpdateCategoryMeta(ctx, &do.CategoryMeta{
				ID:           req.ID,
				Name:         req.Name,
				CategoryType: req.CategoryType,
			})
			handleBizRsp(ctx, nil, err)
		})

		categoryApiGroup.POST("/delete", func(ctx *gin.Context) {
			type ReqJson struct {
				ID int
			}
			var req ReqJson
			if err := ctx.BindJSON(&req); err != nil {
				return
			}
			err := categoryRepo.DeleteCategoryMeta(ctx, req.ID)
			handleBizRsp(ctx, nil, err)
		})

		categoryApiGroup.POST("/list", func(ctx *gin.Context) {
			type ReqJson struct {
				Page          int
				PageSize      int
				Search        string
				Sorts         string
				CategoryTypes []do.CategoryType
			}
			var req ReqJson
			if err := ctx.BindJSON(&req); err != nil {
				return
			}
			listData, total, err := categoryRepo.ListCategoryMeta(ctx, category.ListCategoryMetaParam{
				Page:          req.Page,
				PageSize:      req.PageSize,
				CategoryTypes: req.CategoryTypes,
				Search:        req.Search,
				Sorts:         req.Sorts,
			})
			handleBizListRsp(ctx, listData, total, err)
		})
	}
}
